﻿$(document).ready(function (){
	//ai
	var lastask ="";
	var testRobot = "Alan";
	var username = "U";
	$("#textview").focus();
	$(document).keyup(function(event){
		var focusId = $("textarea:focus").attr("id");
		var botId = userProfile.robot.id;
		var currentText = $("#textview");
		var currentChat = $("#chatview");
		if(focusId == "parktextview") {
			botId = $("#currentBotsID").attr("value");
			currentText = $("#parktextview");
			currentChat = $("#parkchatview2");			
		}
		if(event.keyCode == 13){
			var ask = currentText.attr("value");
			while(ask.indexOf("?") >= 0 || ask.indexOf("#") >= 0 || ask.indexOf("%") >= 0){
				ask = ask.replace("?","");
				ask = ask.replace("#","");
				ask = ask.replace("%","");
			}
			//teach
			if(ask.substr(0,6) == "teach:"){
				var answer = ask.substr(6);
				var answer = answer.substr(0,answer.length-1);
				if(lastask.length == 0 || answer.length == 0){
					alert("fail");
				}else{
					//ai
					$.ajax({
						type:"GET",
						url:"index/teach/ask/"+lastask+"/answer/"+answer+"/id/"+botId,
						async:true,
						beforeSend:function loading(){
						},
						success:function(v){
							if(v == "s"){
								currentChat.append(testRobot + ": i get it\n\n");
							}
						},
						error:function(){
						}
					});						
				}
			}else{
				//chat
				$.ajax({
					type:"GET",
					url:"index/chat/text/"+ask+"/id/"+botId,
					async:true,
					beforeSend:function loading(){
					},
					success:function(v){
						currentChat.append(username + ":" + ask);
						currentChat.append(testRobot + ":" + v +"(U can use 'teach:' function)\n\n");
						lastask = ask.substr(0,ask.length-1);
						$.ajax({
							type:"GET",
							url:"index/learn/ask/"+lastask+"/answer/"+v+"/id/"+botId,
							async:true,
							beforeSend:function loading(){
							},
							success:function(v){
							},
							error:function(){
							}
						});	
					},
						error:function(){
					}
				});	
			}		
			currentText.attr("value","");
		}		
	}); 
	
	
});